package t;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import org.nutz.json.Json;

import com.kerbores.utils.entries.Result;

/**
 * @author 王贵源
 *
 * @email kerbores@kerbores.com
 *
 * @description //TODO 类描述
 * 
 * @copyright 内部代码,禁止转发
 *
 *
 * @time 2016年1月29日 下午5:27:11
 */
@ClientEndpoint
public class W {
	@OnOpen
	public void onOpen(Session session) {

		Result r = Json.fromJson(Result.class, "");
		if (r.isSuccess()) {
			System.err.println(r.getData());
		} else {
			System.err.println(r.getReason());
		}

		System.out.println("Connected to endpoint:" + session.getBasicRemote());
		try {
			session.getBasicRemote().sendText("Hello");
		} catch (IOException ex) {
		}
	}

	@OnMessage
	public void onMessage(String message) {
		System.out.println(message);
	}

	@OnError
	public void onError(Throwable t) {
		t.printStackTrace();
	}

	public static void main(String[] args) {
		W client = new W();
		client.start();

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input = "";
		try {
			do {
				input = br.readLine();
				if (!input.equals("exit"))
					client.session.getBasicRemote().sendText(input);

			} while (!input.equals("exit"));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Session session;

	protected void start() {

		WebSocketContainer container = ContainerProvider.getWebSocketContainer();

		String uri = "ws://127.0.0.1:8080/websocket.ws/ROOT/relationId/12345";
		System.out.println("Connecting to " + uri);
		try {
			session = container.connectToServer(W.class, URI.create(uri));
		} catch (DeploymentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
